package com.wj.chatroom.controller;
import com.wj.chatroom.mapper.UserMapper;
import com.wj.chatroom.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/login")
    public Object login(String username, String password, HttpServletRequest req){
        User user = userMapper.selectByName(username);
        log.info("登录成功"+user.getUsername());
        if(user==null||!user.getPassword().equals(password)){
            System.out.println("登录失败，用户名或密码错误!"+user);
            //返回一个空对象，初始化的时候就是""
            return new User();
        }
        //这里设置为true，创建一个新的会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        user.setPassword("");
        return user;
    }
    @RequestMapping("/register")
    public Object register(String username, String password){
        User user = null;
        try{
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int ret = userMapper.insert(user);
            System.out.println("注册ret"+ret);
            user.setPassword("");
        }catch (DuplicateKeyException e){
            user = new User();
        }
        return user;
    }
    @RequestMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest req){
        //这里设置为false,是从已有的会话中获取，而不是创建新的会话，如果会话不存在就返回null
        HttpSession session = req.getSession(false);
        if(session==null){
            System.out.println("用户未登录，获取不到sessio对象");
            return new User();
        }
        User  user = (User) session.getAttribute("user");
        if(user==null){
            System.out.println("当前获取不到sessio对象");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}